// filter.js - 专业滤镜算法

// 棕褐色滤镜（统一CSS与Canvas效果）
export const applySepia = async (canvasId, width, height, componentInstance) => {
    try {
        const { data: buffer } = await new Promise((resolve, reject) => {
            uni.canvasGetImageData({
                canvasId,
                x: 0,
                y: 0,
                width,
                height,
                success: resolve,
                fail: reject
            }, componentInstance);
        });

        const srcData = new Uint8ClampedArray(buffer);
        const destData = new Uint8ClampedArray(buffer.byteLength);

        for (let i = 0; i < srcData.length; i += 4) {
            // 棕褐色调公式（与CSS sepia滤镜算法一致）
            const r = srcData[i] * 0.393 + srcData[i + 1] * 0.769 + srcData[i + 2] * 0.189;
            const g = srcData[i] * 0.349 + srcData[i + 1] * 0.686 + srcData[i + 2] * 0.168;
            const b = srcData[i] * 0.272 + srcData[i + 1] * 0.534 + srcData[i + 2] * 0.131;
            
            // 统一增强参数（与CSS brightness/contrast一致）
            destData[i] = Math.min(255, r * 1.05);    // R (CSS brightness 1.05)
            destData[i + 1] = Math.min(255, g * 0.95);  // G (CSS contrast 0.95)
            destData[i + 2] = Math.min(255, b * 0.9);   // B (CSS saturate 0.9)
            destData[i + 3] = srcData[i + 3];           // Alpha
        }

        await new Promise((resolve, reject) => {
            uni.canvasPutImageData({
                canvasId,
                x: 0,
                y: 0,
                width,
                height,
                data: destData,
                success: resolve,
                fail: reject
            }, componentInstance);
        });
    } catch (err) {
        console.error('棕褐色滤镜处理失败:', err);
        throw new Error('FILTER_PROCESS_FAIL');
    }
};

// 黑白滤镜（统一CSS与Canvas效果）
export const applyGrayscale = async (canvasId, width, height, componentInstance) => {
    try {
        const { data: buffer } = await new Promise((resolve, reject) => {
            uni.canvasGetImageData({
                canvasId,
                x: 0,
                y: 0,
                width,
                height,
                success: resolve,
                fail: reject
            }, componentInstance);
        });

        const srcData = new Uint8ClampedArray(buffer);
        const destData = new Uint8ClampedArray(buffer.byteLength);

        for (let i = 0; i < srcData.length; i += 4) {
            const r = srcData[i];
            const g = srcData[i + 1];
            const b = srcData[i + 2];
            
            // 使用CSS grayscale标准算法（与CSS滤镜一致）
            const gray = 0.2126 * r + 0.7152 * g + 0.0722 * b;
            
            destData[i] = gray;     // R
            destData[i + 1] = gray; // G
            destData[i + 2] = gray; // B
            destData[i + 3] = srcData[i + 3]; // Alpha
        }

        await new Promise((resolve, reject) => {
            uni.canvasPutImageData({
                canvasId,
                x: 0,
                y: 0,
                width,
                height,
                data: destData,
                success: resolve,
                fail: reject
            }, componentInstance);
        });
    } catch (err) {
        console.error('黑白滤镜处理失败:', err);
        throw new Error('FILTER_PROCESS_FAIL');
    }
};

// 冷调滤镜（统一CSS与Canvas效果）
// export const applyCoolTone = async (canvasId, width, height, componentInstance) => {
//     try {
//       const buffer = await new Promise((resolve, reject) => {
//         uni.canvasGetImageData({
//           canvasId,
//           x: 0,
//           y: 0,
//           width,
//           height,
//           success: resolve,
//           fail: reject
//         }, componentInstance);
//       });
  
//       const srcData = new Uint8ClampedArray(buffer);
//       const destData = new Uint8ClampedArray(buffer.byteLength);
  
//       for (let i = 0; i < srcData.length; i += 4) {
//         const r = srcData[i];
//         const g = srcData[i + 1];
//         const b = srcData[i + 2];
        
//         // 冷色调调整公式
//         destData[i] = Math.min(255, r * 0.8);      // 减少红色 (20%)
//         destData[i + 1] = Math.min(255, g * 1.1); // 增强绿色 (10%)
//         destData[i + 2] = Math.min(255, b * 1.3); // 显著增强蓝色 (30%)
//         destData[i + 3] = srcData[i + 3];         // 保持Alpha通道
//       }
  
//       await new Promise((resolve, reject) => {
//         uni.canvasPutImageData({
//           canvasId,
//           x: 0,
//           y: 0,
//           width,
//           height,
//           data: destData,
//           success: resolve,
//           fail: reject
//         }, componentInstance);
//       });
//     } catch (err) {
//       console.error('冷色调滤镜处理失败:', err);
//       throw new Error('FILTERPROCESSFAIL');
//     }
//   };
  
export const applyCoolTone = async (canvasId, width, height, componentInstance) => {
    try {
      const buffer = await new Promise((resolve, reject) => {
        uni.canvasGetImageData(
          canvasId,
          {
            x: 0,
            y: 0,
            width,
            height,
            success: resolve,
            fail: reject
          },
          componentInstance
        );
      });
  
      const srcData = new Uint8ClampedArray(buffer);
      const destData = new Uint8ClampedArray(buffer.byteLength);
      
      // 滤镜参数（严格按新顺序）
      const contrastFactor = 1.25;
      const saturateFactor = 0.7;
      const hueRotate = 10; // 度数
      const sepiaFactor = 0.3;
      const brightnessFactor = 0.95;
      
      // 预计算色相旋转的三角函数值
      const cos = Math.cos(hueRotate * Math.PI / 180);
      const sin = Math.sin(hueRotate * Math.PI / 180);
      
      // 构建饱和度矩阵
      const saturateMatrix = [
        (1 - saturateFactor) + saturateFactor * 0.213,
        (1 - saturateFactor) * 0.715,
        (1 - saturateFactor) * 0.072,
        (1 - saturateFactor) * 0.213,
        (1 - saturateFactor) + saturateFactor * 0.715,
        (1 - saturateFactor) * 0.072,
        (1 - saturateFactor) * 0.213,
        (1 - saturateFactor) * 0.715,
        (1 - saturateFactor) + saturateFactor * 0.072
      ];
      
      // 构建色相旋转矩阵
      const hueRotateMatrix = [
        cos + (1 - cos) * 0.213,
        (1 - cos) * 0.715 - sin * 0.143,
        (1 - cos) * 0.072 + sin * 0.787,
        (1 - cos) * 0.213 + sin * 0.787,
        cos + (1 - cos) * 0.715,
        (1 - cos) * 0.072 - sin * 0.143,
        (1 - cos) * 0.213 - sin * 0.143,
        (1 - cos) * 0.715 + sin * 0.143,
        cos + (1 - cos) * 0.072
      ];
      
      // 构建深褐色矩阵
      const sepiaMatrix = [
        (1 - sepiaFactor) + sepiaFactor * 0.393,
        sepiaFactor * 0.769,
        sepiaFactor * 0.189,
        sepiaFactor * 0.349,
        (1 - sepiaFactor) + sepiaFactor * 0.686,
        sepiaFactor * 0.168,
        sepiaFactor * 0.272,
        sepiaFactor * 0.534,
        (1 - sepiaFactor) + sepiaFactor * 0.131
      ];
      
      // 应用滤镜（严格按指定顺序）
      for (let i = 0; i < srcData.length; i += 4) {
        let r = srcData[i];
        let g = srcData[i + 1];
        let b = srcData[i + 2];
        
        // 1. 应用对比度
        r = (r - 128) * contrastFactor + 128;
        g = (g - 128) * contrastFactor + 128;
        b = (b - 128) * contrastFactor + 128;
        
        // 2. 应用饱和度
        const newR1 = saturateMatrix[0] * r + saturateMatrix[1] * g + saturateMatrix[2] * b;
        const newG1 = saturateMatrix[3] * r + saturateMatrix[4] * g + saturateMatrix[5] * b;
        const newB1 = saturateMatrix[6] * r + saturateMatrix[7] * g + saturateMatrix[8] * b;
        r = newR1;
        g = newG1;
        b = newB1;
        
        // 3. 应用色相旋转
        const newR2 = hueRotateMatrix[0] * r + hueRotateMatrix[1] * g + hueRotateMatrix[2] * b;
        const newG2 = hueRotateMatrix[3] * r + hueRotateMatrix[4] * g + hueRotateMatrix[5] * b;
        const newB2 = hueRotateMatrix[6] * r + hueRotateMatrix[7] * g + hueRotateMatrix[8] * b;
        r = newR2;
        g = newG2;
        b = newB2;
        
        // 4. 应用深褐色
        const newR3 = sepiaMatrix[0] * r + sepiaMatrix[1] * g + sepiaMatrix[2] * b;
        const newG3 = sepiaMatrix[3] * r + sepiaMatrix[4] * g + sepiaMatrix[5] * b;
        const newB3 = sepiaMatrix[6] * r + sepiaMatrix[7] * g + sepiaMatrix[8] * b;
        r = newR3;
        g = newG3;
        b = newB3;
        
        // 5. 应用亮度
        r = r * brightnessFactor;
        g = g * brightnessFactor;
        b = b * brightnessFactor;
        
        // 钳制到0-255范围
        destData[i] = Math.min(255, Math.max(0, r));
        destData[i + 1] = Math.min(255, Math.max(0, g));
        destData[i + 2] = Math.min(255, Math.max(0, b));
        destData[i + 3] = srcData[i + 3]; // 保持Alpha通道
      }
      
      await new Promise((resolve, reject) => {
        uni.canvasPutImageData(
          canvasId,
          {
            x: 0,
            y: 0,
            width,
            height,
            data: destData,
            success: resolve,
            fail: reject
          },
          componentInstance
        );
      });
    } catch (err) {
      console.error('CSS滤镜处理失败:', err);
      throw new Error('FILTERPROCESSFAIL');
    }
  };
  
// 暖阳滤镜（统一CSS与Canvas效果）
export const applyWarmSunlight = async (canvasId, width, height, componentInstance) => {
    try {
        const { data: buffer } = await new Promise((resolve, reject) => {
            uni.canvasGetImageData({
                canvasId,
                x: 0,
                y: 0,
                width,
                height,
                success: resolve,
                fail: reject
            }, componentInstance);
        });

        const srcData = new Uint8ClampedArray(buffer);
        const destData = new Uint8ClampedArray(buffer.byteLength);

        // 统一参数（与CSS滤镜一致）
        const sepiaIntensity = 0.3;    // CSS sepia(30%)
        const brightnessFactor = 1.05; // CSS brightness(1.05)
        const saturateFactor = 1.2;    // CSS saturate(1.2)
        const hueRotate = -10;          // CSS hue-rotate(-10deg)

        for (let i = 0; i < srcData.length; i += 4) {
            let r = srcData[i];
            let g = srcData[i + 1];
            let b = srcData[i + 2];

            // 应用棕褐色效果（与CSS sepia一致）
            const sepiaR = r * 0.393 + g * 0.769 + b * 0.189;
            const sepiaG = r * 0.349 + g * 0.686 + b * 0.168;
            const sepiaB = r * 0.272 + g * 0.534 + b * 0.131;
            
            r = sepiaR * sepiaIntensity + r * (1 - sepiaIntensity);
            g = sepiaG * sepiaIntensity + g * (1 - sepiaIntensity);
            b = sepiaB * sepiaIntensity + b * (1 - sepiaIntensity);

            // 应用亮度（与CSS一致）
            r *= brightnessFactor;
            g *= brightnessFactor;
            b *= brightnessFactor;

            // 应用饱和度（与CSS一致）
            const gray = 0.2126 * r + 0.7152 * g + 0.0722 * b;
            r = gray + (r - gray) * saturateFactor;
            g = gray + (g - gray) * saturateFactor;
            b = gray + (b - gray) * saturateFactor;

            // 应用色相旋转（与CSS一致）
            const θ = hueRotate * Math.PI / 180;
            const cosθ = Math.cos(θ);
            const sinθ = Math.sin(θ);
            
            const nr = r * (0.213 + cosθ * 0.787 - sinθ * 0.213) +
                      g * (0.715 - cosθ * 0.715 - sinθ * 0.715) +
                      b * (0.072 - cosθ * 0.072 + sinθ * 0.928);
            
            const ng = r * (0.213 - cosθ * 0.213 + sinθ * 0.143) +
                      g * (0.715 + cosθ * 0.285 + sinθ * 0.140) +
                      b * (0.072 - cosθ * 0.072 - sinθ * 0.283);
            
            const nb = r * (0.213 - cosθ * 0.213 - sinθ * 0.787) +
                      g * (0.715 - cosθ * 0.715 + sinθ * 0.715) +
                      b * (0.072 + cosθ * 0.928 + sinθ * 0.072);

            destData[i] = Math.min(255, Math.max(0, nr));  // R
            destData[i + 1] = Math.min(255, Math.max(0, ng)); // G
            destData[i + 2] = Math.min(255, Math.max(0, nb)); // B
            destData[i + 3] = srcData[i + 3]; // Alpha
        }

        await new Promise((resolve, reject) => {
            uni.canvasPutImageData({
                canvasId,
                x: 0,
                y: 0,
                width,
                height,
                data: destData,
                success: resolve,
                fail: reject
            }, componentInstance);
        });
    } catch (err) {
        console.error('暖阳滤镜处理失败:', err);
        throw new Error('FILTER_PROCESS_FAIL');
    }
};

// 小清新滤镜（统一CSS与Canvas效果）
export const applyFreshFilter = async (canvasId, width, height, componentInstance) => {
    try {
        const { data: buffer } = await new Promise((resolve, reject) => {
            uni.canvasGetImageData({
                canvasId,
                x: 0,
                y: 0,
                width,
                height,
                success: resolve,
                fail: reject
            }, componentInstance);
        });

        const srcData = new Uint8ClampedArray(buffer);
        const destData = new Uint8ClampedArray(buffer.byteLength);

        // 统一参数（与CSS滤镜一致）
        const brightnessFactor = 1.1;  // CSS brightness(1.1)
        const contrastFactor = 0.95;   // CSS contrast(0.95)
        const saturateFactor = 1.2;    // CSS saturate(1.2)
        const hueRotate = 15;           // CSS hue-rotate(15deg)

        for (let i = 0; i < srcData.length; i += 4) {
            let r = srcData[i];
            let g = srcData[i + 1];
            let b = srcData[i + 2];
            
            // 应用亮度（与CSS一致）
            r *= brightnessFactor;
            g *= brightnessFactor;
            b *= brightnessFactor;

            // 应用对比度（与CSS一致）
            r = (r - 128) * contrastFactor + 128;
            g = (g - 128) * contrastFactor + 128;
            b = (b - 128) * contrastFactor + 128;

            // 应用饱和度（与CSS一致）
            const gray = 0.2126 * r + 0.7152 * g + 0.0722 * b;
            r = gray + (r - gray) * saturateFactor;
            g = gray + (g - gray) * saturateFactor;
            b = gray + (b - gray) * saturateFactor;

            // 应用色相旋转（与CSS一致）
            const θ = hueRotate * Math.PI / 180;
            const cosθ = Math.cos(θ);
            const sinθ = Math.sin(θ);
            
            const nr = r * (0.213 + cosθ * 0.787 - sinθ * 0.213) +
                      g * (0.715 - cosθ * 0.715 - sinθ * 0.715) +
                      b * (0.072 - cosθ * 0.072 + sinθ * 0.928);
            
            const ng = r * (0.213 - cosθ * 0.213 + sinθ * 0.143) +
                      g * (0.715 + cosθ * 0.285 + sinθ * 0.140) +
                      b * (0.072 - cosθ * 0.072 - sinθ * 0.283);
            
            const nb = r * (0.213 - cosθ * 0.213 - sinθ * 0.787) +
                      g * (0.715 - cosθ * 0.715 + sinθ * 0.715) +
                      b * (0.072 + cosθ * 0.928 + sinθ * 0.072);

            destData[i] = Math.min(255, Math.max(0, nr));  // R
            destData[i + 1] = Math.min(255, Math.max(0, ng)); // G
            destData[i + 2] = Math.min(255, Math.max(0, nb)); // B
            destData[i + 3] = srcData[i + 3]; // Alpha
        }

        await new Promise((resolve, reject) => {
            uni.canvasPutImageData({
                canvasId,
                x: 0,
                y: 0,
                width,
                height,
                data: destData,
                success: resolve,
                fail: reject
            }, componentInstance);
        });
    } catch (err) {
        console.error('小清新滤镜处理失败:', err);
        throw new Error('FILTER_PROCESS_FAIL');
    }
};
